'use strict';

const { Service } = require('egg');
const ModelName = 'Post'
class RouterService extends Service {
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order:[
                // id 降序
                ['sort','DESC']
            ],
            include: [
                {
                    model: this.ctx.model.User,
                    as: 'user',
                },
                {
                    model: this.ctx.model.PostJoin,
                    as: 'postJoinList',
                }
            ]
        });
    }
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['sort','DESC']
            ],
            include: [
                {
                    model: this.ctx.model.User,
                    as: 'user',
                },
            ]
        });
    }
    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
    }
    async create(data) {
        if (data.user_id) {
            const user = await this.ctx.model.User.findOne({
                where: {
                    id: data.user_id,
                },
            });
            if (!user) {
                throw new Error('用户不存在');
            }
            if (user.audit !== 1) {
                throw new Error('用户未审核通过');
            }
        } else {
            throw new Error('用户不存在');
        }
        if (!data.start_time) {
            delete data.start_time
        }
        if (!data.end_time) {
            delete data.end_time
        }
        if (!data.day) {
            data.day = 0
        }
        return this.ctx.model[ModelName].create(data);
    }
    async update(id, data) {
        if (data.user_id) {
            const user = await this.ctx.model.User.findOne({
                where: {
                    id: data.user_id,
                },
            });
            if (!user) {
                throw new Error('用户不存在');
            }
            if (user.audit !== 1) {
                throw new Error('用户未审核通过');
            }
        } else {
            throw new Error('用户不存在');
        }
        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }
    async sort(id) {
        // 查找数据库中排序最大的数据的sort值
        const maxSort = await this.ctx.model[ModelName].max('sort');
        // 本次排序值为最大值+1
        const sort = maxSort + 1;
        return await this.ctx.model[ModelName].update({ sort }, { where: { id } });
    }
    async deleteById(id) {
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }
}

module.exports = RouterService;
